package cn.juque.jdfsystem.helper;

import cn.hutool.core.io.FileUtil;
import cn.juque.common.constants.MessageEnum;
import cn.juque.common.constants.StringConstants;
import cn.juque.common.disruptor.DisruptorHandler;
import cn.juque.common.exception.AppException;
import cn.juque.jdfsystem.bo.FileInfoSaveBO;
import cn.juque.jdfsystem.cache.FileInfoCache;
import cn.juque.jdfsystem.config.JdfConfig;
import cn.juque.jdfsystem.disruptor.bo.FileAddBodyBO;
import cn.juque.jdfsystem.disruptor.bo.SendMsgBodyBO;
import cn.juque.jdfsystem.disruptor.event.SendMsgDisruptorEventServiceImpl;
import cn.juque.jdfsystem.entity.FileInfo;
import cn.juque.jdfsystem.enums.HttpMessageTypeEnum;
import cn.juque.jdfsystem.service.IFileInfoService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>FileInfoHelper</li>
 * </ul>
 * @date 2023-01-11 20:15:50
 **/
@Component("fileInfoHelper")
public class FileInfoHelper {

    @Resource
    private IFileInfoService fileInfoService;

    @Resource
    private JdfConfig jdfConfig;

    @Resource
    private DisruptorHandler disruptorHandler;

    @Resource
    private FileInfoCache fileInfoCache;

    public String saveFileInfo(FileInfoSaveBO saveBO) {
        String fileId = this.fileInfoService.saveInfo(saveBO);
        // 发消息
        FileAddBodyBO fileAddBodyBO = new FileAddBodyBO();
        fileAddBodyBO.setNodeName(this.jdfConfig.getNodeName());
        fileAddBodyBO.setFileId(fileId);
        SendMsgBodyBO<FileAddBodyBO> sendMsgBodyBO = new SendMsgBodyBO<>();
        sendMsgBodyBO.setPayload(fileAddBodyBO);
        sendMsgBodyBO.setMessageTypeEnum(HttpMessageTypeEnum.FILE_ADD);
        sendMsgBodyBO.setBusinessEventService(SendMsgDisruptorEventServiceImpl.BEAN);
        this.disruptorHandler.publish(sendMsgBodyBO);

        return fileId;
    }

    /**
     * 获取文件详情
     *
     * @param fileId 文件ID
     * @return FileInfo
     */
    public FileInfo detail(String fileId) {
        FileInfo fileInfo = this.fileInfoCache.getFileInfo(fileId);
        if (null == fileInfo) {
            fileInfo = this.fileInfoService.detail(fileId);
            this.fileInfoCache.putForFile(fileInfo);
        }
        return fileInfo;
    }

    /**
     * 删除文件
     *
     * @param fileInfo 文件信息
     */
    public void deleteInfo(FileInfo fileInfo) {
        this.fileInfoService.deleteFile(fileInfo);
    }

    /**
     * 获取文件对象
     *
     * @param fileInfo 文件信息
     * @return File
     */
    public File getFile(FileInfo fileInfo) {
        if (null == fileInfo) {
            throw new AppException(MessageEnum.PARAM_NULL.getCode(), "文件不存在");
        }
        String fileName = fileInfo.getId() + StringConstants.POINT + fileInfo.getFileExt();
        return FileUtil.file(fileInfo.getServerPath(), fileName);
    }
}
